<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * 定时检测订单预警时间
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/25
 * Time: 16:52
 */

namespace SDXApi\Controller;
use Think\Controller;
use Think\Model;

class AlarmcheckController extends Controller
{
    public function check(){
        $this->del_log();               //删除日志
        $this->check_alarm();           //检查预警信息
        $this->check_alarm_type_4();    //插入自提单预警
        $this->check_alarm_type_wrong();    //插入问题单预警
        //$this->check_hook_goods();      //检查商品库存和登记数
        $this->operate_goods();         //检查运营平台数据
        $this->operate_goods_weight();    //
        $this->check_order_weight();    //
    }



    public function check_order_weight(){
        $where= "order_status !=2 and  shipping_status != 2  and pay_status in(2,3) and shipping_id = 3";
        $order_sn = M("order_info")->where($where)->field("order_sn,order_id")->select();
        foreach ($order_sn as $value){
            $goods_info = A("Autoserver")->get_goods_list_real($value['order_id'],false,"name");
            if($goods_info['goods_weight']>10){
                $values['order_sn'] = $value['order_sn'];
                $this->w_alarm_log($values,10);
            }
        }
    }
    /**
     * 供应商结算报表(SupsettlementController_supsettlement_prepare)
     * * http://apidev.cyb.cn/index.php?s=/Alarmcheck/supsettlement_prepare/
     * * 调用说明：正点前10分钟执行，比如12点查看数据，11:50分执行此任务;
     *
     * @author ^2_3^
     */
    public function supsettlement_prepare() {
        set_time_limit(0);

        /// 上次时间
        $start_date = I('request.start_date', '', 'trim');
        $last_sql = "
            SELECT MAX(oge.record_time) AS last_time FROM sdx_order_goods_exinfo oge
        ";
        $last_arr = M()->query( $last_sql );
        if( !empty($last_arr[0]['last_time']) ) {
            $last_time = $last_arr[0]['last_time'];

        }else if( !empty($start_date) ) {
            $last_time = strtotime( $start_date ) - 28800;

        }else {
            $start_date = date('Y-m-d', time());
            $last_time = strtotime( $start_date )- 28800;
        }


        //-/ 过滤条件
        $where = '';
        $ref_where = ''; //退款条件;
        if( !empty($last_time) ) {
            $where .= " AND oi.shipping_time >= {$last_time} ";
            $ref_where .= " AND rd.opt_time >= {$last_time} ";
        }

        // 调用时间
        $now_time = gmtime();

        //-/ 表前缀
        $db_prefix = C('DB_PREFIX');

        /// 商品销量
        $tmp_order = "
            SELECT
                oge.id AS oge_id,
                oi.order_sn,
                oi.order_id,
                og.rec_id AS og_id,
                og.goods_id,
                og.goods_sn,
                og.goods_name,
                g.sources AS goods_sources,
                og.goods_price,
                og.goods_number
            FROM
                {$db_prefix}order_info oi
                LEFT JOIN {$db_prefix}order_goods og ON og.order_id = oi.order_id
                LEFT JOIN {$db_prefix}users u ON u.user_id = oi.user_id
                LEFT JOIN {$db_prefix}goods g ON g.goods_id = og.goods_id
                LEFT JOIN {$db_prefix}order_goods_exinfo oge
                    ON oge.order_id = og.order_id
                    AND oge.order_goods_id = og.rec_id
                    AND oge.goods_id = og.goods_id
            WHERE u.user_name NOT LIKE 'wx_196%' {$where}
                AND oi.pay_status IN (2, 3, 4)
                AND oi.order_status IN (1, 5)
            GROUP BY CONCAT(oi.order_id, '_', og.rec_id, '_', og.goods_id)
        ";
        $tmp_pro_desc = "
    		SELECT
    			wp.id AS wp_id,
    			wp.procurement_sn,
    			wp.supplier_id,
    			ws.name AS wsname,
    			wp.add_userid,
    			wp.add_time AS wp_add_time,
    			FROM_UNIXTIME( wp.add_time+28800, '%Y-%m-%d %H:%i:%s') AS wp_add_date,
    			wp.settlement_method,
    			wp.settlement_time,
    			wpd.wid,
    			wpd.goods_id,
    			wpd.goods_sn,
    			wpd.goods_name,
    			wpd.goods_weight,
    			wpd.spec_value,
    			wpd.spec_unit,
    			wpd.total_quantity,
    			wpd.actual_inventory_quantity,
    			wpd.procurement_price,
    			wpd.production_date,
    			wpd.status AS wpd_status
    		FROM
    			{$db_prefix}warehouse_procurement wp,
    			{$db_prefix}warehouse_procurement_detail wpd,
    			{$db_prefix}warehouse_supplier ws
    		WHERE
    			wp.id = wpd.procurement_id
    			AND wp.supplier_id = ws.id
    			AND wpd.status in (1, 2, 4)
    		ORDER BY wp.id DESC
        ";
        $tmp_pro = "
            SELECT
                wp_id,
                procurement_sn,
                supplier_id,
                wsname,
                add_userid,
                wp_add_time,
                wp_add_date,
                settlement_method,
                settlement_time,
                wid,
                goods_id,
                goods_sn,
                goods_name,
                goods_weight,
                spec_value,
                spec_unit,
                total_quantity,
                actual_inventory_quantity,
                procurement_price,
                production_date,
                wpd_status
            FROM ({$tmp_pro_desc}) tmp_pro_desc
            GROUP BY goods_id
        ";
        //-/ 订单商品采购信息
        $order_sql = "
            SELECT
                order_id,
                og_id,
                tmp_order.goods_id,
                tmp_order.goods_name,
                tmp_order.goods_sn,
                goods_sources,
                wp_id,
                procurement_sn,
                supplier_id,
                wsname,
                settlement_method,
                procurement_price,
                '{$now_time}'
            FROM ({$tmp_order}) tmp_order
            LEFT JOIN ({$tmp_pro}) tmp_pro ON tmp_order.goods_id = tmp_pro.goods_id
            WHERE oge_id IS NULL
        ";

        /// 添加 订单商品扩展表(sdx_order_goods_exinfo) 商品销售数据
        $oge_insert_sql = "
            INSERT INTO sdx_order_goods_exinfo (
                order_id,
                order_goods_id,
                goods_id,
                goods_name,
                goods_sn,
                goods_sources,
                wp_id,
                wp_procurement_sn,
                supplier_id,
                supplier_name,
                settlement_method,
                procurement_price,
                record_time
            ) {$order_sql}
        ";
        $order_flag = M()->execute( $oge_insert_sql );

        /// 添加 供应商结算表(sdx_supplier_settlement) 数据
        //-/ 销售数据
        $tmp_oge_sql = "
            SELECT
                oi.order_id,
                oge.wp_id,
                oge.wp_procurement_sn,
                oi.platform,
                oge.supplier_id,
                oge.supplier_name,
                og.goods_id,
                og.goods_name,
                og.goods_sn,
                oge.goods_sources,
                oge.settlement_method,
                oge.procurement_price,
                og.goods_price,
                og.goods_number
            FROM
                {$db_prefix}order_info oi
                LEFT JOIN {$db_prefix}order_goods og ON og.order_id = oi.order_id
                LEFT JOIN {$db_prefix}users u ON u.user_id = oi.user_id
                LEFT JOIN {$db_prefix}order_goods_exinfo oge
                    ON oge.order_id = og.order_id
                    AND oge.order_goods_id = og.rec_id
                    AND oge.goods_id = og.goods_id
            WHERE u.user_name NOT LIKE 'wx_196%' {$where}
                AND oge.id is not null
                AND oi.pay_status IN (2, 3, 4)
                AND oi.order_status IN (1, 5)
        ";
        $oge_sql = "
            SELECT
                wp_id,
                wp_procurement_sn,
                platform,
                supplier_id,
                supplier_name,
                goods_id,
                goods_name,
                goods_sn,
                goods_sources,
                settlement_method,
                procurement_price,
                goods_price,
                SUM(goods_number) AS sum_goods_number,
                '{$now_time}',
                GROUP_CONCAT(order_id) as extension
            FROM ({$tmp_oge_sql}) tmp_oge
            GROUP BY platform, supplier_id, goods_id, goods_sources, settlement_method, procurement_price, goods_price
        ";
        //-/ 添加 供应商结算表 数据
        $ss_insert_sql = "
            INSERT INTO sdx_supplier_settlement (
                wp_id,
                wp_procurement_sn,
                platform,
                supplier_id,
                supplier_name,
                goods_id,
                goods_name,
                goods_sn,
                goods_sources,
                settlement_method,
                procurement_price,
                goods_price,
                goods_num,
                statistics_time,
                extension
            ) {$oge_sql}
        ";
        $order_flag && M()->execute( 'set session group_concat_max_len = 3072' );
        $order_flag && $ss_flag = M()->execute( $ss_insert_sql );

        /// 退款处理
        //-/ 商品退款
        $tmp_refund_sql = "
            SELECT
                rd.order_id,
                rd.order_goods_id,
                rd.goods_id,
                rd.goods_name,
                rd.goods_sn,
                g.sources
            FROM
                {$db_prefix}refund_detail rd
                LEFT JOIN {$db_prefix}order_goods og 
                    ON og.order_id = rd.order_id 
                    AND og.rec_id = rd.order_goods_id 
                    AND og.goods_id = rd.goods_id
                LEFT JOIN {$db_prefix}goods g ON g.goods_id = rd.goods_id
                LEFT JOIN {$db_prefix}order_goods_exinfo oge
                    ON oge.order_id = og.order_id
                    AND oge.order_goods_id = og.rec_id
                    AND oge.goods_id = og.goods_id
            WHERE oge.id is NULL {$ref_where}
            GROUP BY CONCAT( rd.order_id, '_', rd.order_goods_id, '_', og.goods_id)
            ORDER BY order_id DESC
        ";
        $refund_sql = "
            SELECT
                order_id,
                order_goods_id,
                tmp_refund.goods_id,
                tmp_refund.goods_name,
                tmp_refund.goods_sn,
                sources,
                wp_id,
                procurement_sn,
                supplier_id,
                wsname,
                settlement_method,
                procurement_price,
                '{$now_time}'
            FROM ({$tmp_refund_sql}) tmp_refund
            LEFT JOIN ({$tmp_pro}) tmp_pro ON tmp_refund.goods_id = tmp_pro.goods_id
        ";

        /// 添加 订单商品扩展表(sdx_order_goods_exinfo) 退款退货数据
        $ref_oge_insert_sql = "
            INSERT INTO sdx_order_goods_exinfo (
                order_id,
                order_goods_id,
                goods_id,
                goods_name,
                goods_sn,
                goods_sources,
                wp_id,
                wp_procurement_sn,
                supplier_id,
                supplier_name,
                settlement_method,
                procurement_price,
                record_time
            ) {$refund_sql}
        ";
        $refund_flag = M()->execute( $ref_oge_insert_sql );

        /// 添加 退货商品 供应商结算表(sdx_supplier_settlement) 数据信息
        //-/ 商品退货统计
        $refund_sssql = "
            SELECT
                oge.wp_id,
                oge.wp_procurement_sn,
                oi.platform,
                oge.supplier_id,
                oge.supplier_name,
                rd.goods_id,
                rd.goods_name,
                rd.goods_sn,
                oge.goods_sources,
                oge.settlement_method,
                oge.procurement_price,
                og.goods_price,
                SUM(rd.refund_number) as sum_refund_number,
                1 AS is_back,
                {$now_time} AS statistics_time,
                GROUP_CONCAT(oi.order_id) as extension
            FROM
                {$db_prefix}refund_detail rd
                LEFT JOIN {$db_prefix}order_info oi ON oi.order_id = rd.order_id
                LEFT JOIN {$db_prefix}order_goods og 
                    ON og.order_id = rd.order_id 
                    AND og.rec_id = rd.order_goods_id 
                    AND og.goods_id = rd.goods_id
                LEFT JOIN {$db_prefix}order_goods_exinfo oge
                    ON oge.order_id = og.order_id
                    AND oge.order_goods_id = og.rec_id
                    AND oge.goods_id = og.goods_id
            WHERE oge.id IS NOT NULL {$ref_where}
            GROUP BY oi.platform, oge.supplier_id, rd.goods_id,
            oge.goods_sources, oge.settlement_method, oge.procurement_price, og.goods_price
        ";
        //-/ 添加 退货退款 供应商结算表(sdx_supplier_settlement) 数据
        $refund_insert_sssql = "
            INSERT INTO sdx_supplier_settlement (
                wp_id,
                wp_procurement_sn,
                platform,
                supplier_id,
                supplier_name,
                goods_id,
                goods_name,
                goods_sn,
                goods_sources,
                settlement_method,
                procurement_price,
                goods_price,
                goods_num,
                is_back,
                statistics_time,
                extension
            ) {$refund_sssql}
        ";
        $refund_flag && M()->execute('set session group_concat_max_len = 3072');
        $refund_flag && $refund_ss_flag = M()->execute( $refund_insert_sssql );

        dump( "ss_flag->[{$ss_flag}]; refund_ss_flag->[{$refund_ss_flag}];" );

    }

    /**
     * [0979需求]库存系统-采购 缺货、滞销预警 触发;
     * http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/
     *
     * 缺货滞销 重新触发 http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/all
     * 日销售量数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/gds
     * 缺货数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/gsw
     * 滞销数据    http://apidev.cyb.cn/index.php?s=/Alarmcheck/shortagewarning_unsold_data/type/unsold
     * @param string $trigger_date 触发日期，如2016-11-29;
     * @param string $type 触发类型，all全部触发; gds触发商品日销量数据生成; gsw触发生成数据缺货预警;unsold触发生成数据直销预警;
     * @author ^2_3^
     */
    public function shortagewarning_unsold_data() {
        $flag = false;
        $trigger_date = I("request.trigger_date", '', 'trim');
        if( empty($trigger_date) ) {
            $trigger_date = date("Y-m-d");
        }

        $trigger_time = strtotime( $trigger_date ) - 28800;
        $type = I("request.type", '', 'trim');
        if( empty($trigger_time) ) {
            exit('request error;');
        }

        $db_prefix = C('DB_PREFIX');
        if( $type == "all" ) {
            /// 删除数据
            $all_gds_del = "
                DELETE FROM {$db_prefix}goods_day_sales WHERE pay_date_time != 0;
            ";
            $all_gsw_del = "
                DELETE FROM {$db_prefix}goods_shortage_warning WHERE record_time != 0;
            ";
            $all_guw_sql = "
                DELETE FROM {$db_prefix}goods_unsold_warning WHERE record_time != 0;
            ";
            $all_gds_flag = M()->execute( $all_gds_del );
            $all_gsw_flag = M()->execute( $all_gsw_del );
            $all_guw_flag = M()->execute( $all_guw_sql );
            $all_del_flag = $all_gds_flag && $all_gsw_flag && $all_guw_flag;

            if( $all_del_flag || ($all_gds_flag === 0 && $all_gsw_flag === 0 && $all_guw_flag === 0) ) {
                /// 生成40天日销量数据
                $gds_end_time = $trigger_time;
                $gds_start_time = $gds_end_time - 3456000; //40*24*3600;
                $gds_flag = $this->goods_day_sales_data_add($gds_start_time, $gds_end_time);

                /// 缺货预警数据生成规则：当已经上架商品 库存量 < 预警库存量( 前30天销量/30 * 3 )时，列出缺货预警数据;
                $gsw_end_time = $trigger_time;
                $gsw_start_time = $gsw_end_time - 2592000; //30*24*3600;
                $gds_flag && $gsw_flag = $this->goods_shortage_warning_data_add($gsw_start_time, $gsw_end_time);

                /// 直销预警数据生成规则：当商品在连续前30天内，没有销量，列出滞销预警数据;
                $unsold_end_time = $trigger_time;
                $unsold_start_time = $unsold_end_time- 2592000; //30*24*3600;
                $gds_flag && $unsold_flag = $this->goods_unsold_data_add($unsold_start_time, $unsold_end_time);

                $gds_flag && $gsw_flag && $unsold_flag && $flag = true;
            }

        }else if( $type == "gds" ) {
            /// 生成最近10天商品日销量：先删除已有数据，再添加最新数据，保证数据准确; 16-11-29 -> 16-11-19
            $gds_end_time = $trigger_time;
            $gds_start_time = $gds_end_time - 864000; //10 * 24 * 3600;
            //-/ 删除
            $del_sql = "
            DELETE FROM {$db_prefix}goods_day_sales WHERE pay_date_time >= {$gds_start_time} AND pay_date_time <= {$gds_end_time}
            ";
            $del_flag = M()->execute( $del_sql );
            //-/ 添加
            $add_flag = $this->goods_day_sales_data_add($gds_start_time, $gds_end_time);
            $flag = $add_flag;

        }else if( $type == "gsw" ) {
            $gsw_end_time = $trigger_time;
            $gsw_start_time = $gsw_end_time - 2592000; //30*24*3600;
            $gsw_flag = $this->goods_shortage_warning_data_add($gsw_start_time, $gsw_end_time);
            $flag = $gsw_flag;

        }else if( $type == "unsold" ) {
            $unsold_end_time = $trigger_time;
            $unsold_start_time = $unsold_end_time- 2592000; //30*24*3600;
            $unsold_flag = $this->goods_unsold_data_add($unsold_start_time, $unsold_end_time);
            $flag = $unsold_flag;
        }

        $flag ? exit("1") : exit("0");
    }

    /**
     * 滞销预警商品_数据添加
     *
     * @param string $start_time 销售开始时间戳(零时区)，包含此时间戳数据;
     * @param string $end_time 销售结束日期时间戳(零时区)，不包含此时间戳数据;
     * @author ^2_3^
     */
    private function goods_unsold_data_add($start_time, $end_time) {
        $flag = false;
        if( empty($start_time) || empty($end_time) ) {
            return $flag;
        }

        $db_prefix = C('DB_PREFIX');
        $sql = "
        insert into {$db_prefix}goods_unsold_warning (
            goods_id,
            goods_sn,
            goods_name,
            cat_name,
            sum_practical_num,
            brand_name,
            sum_goods_number,
            begin_time,
            end_time,
            record_time
        )
        SELECT * FROM
        (
            SELECT
                tmp_save.goods_id,
                tmp_save.goods_sn,
                tmp_save.goods_name,
                cat_name,
                IFNULL(sum_practical_num, 0) AS sum_practical_num,
                brand_name,
                sum_goods_number,
                '{$start_time}' AS begin_time,
                '{$end_time}' AS end_time,
                (UNIX_TIMESTAMP()-28800) AS record_time
            FROM
            (
            
                -- 商品库存
                SELECT
                    g.goods_id,
                    g.goods_sn,
                    g.goods_name,
                    SUM(gs.practical_num) AS sum_practical_num,
                    c.cat_name,
                    b.brand_name
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_storage gs ON g.goods_id = gs.goods_id
                LEFT JOIN {$db_prefix}category c ON g.cat_id = c.cat_id
                LEFT JOIN {$db_prefix}brand b ON g.brand_id = b.brand_id
                WHERE g.is_on_sale = 1 AND g.is_delete = 0
                GROUP BY g.goods_id
                
            ) tmp_save
            LEFT JOIN
            (
            
                -- 商品日销量
                SELECT
                    gds.goods_id,
                    gds.goods_sn,
                    gds.goods_name,
                    SUM(gds.sum_goods_number) AS sum_goods_number
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_day_sales gds ON gds.goods_id = g.goods_id
                WHERE gds.pay_date_time >= {$start_time}
                AND gds.pay_date_time <= {$end_time}
                AND g.is_on_sale = 1
                AND g.is_delete = 0
                GROUP BY gds.goods_id
                
            ) tmp_sales ON tmp_sales.goods_id = tmp_save.goods_id
        ) tmp WHERE sum_goods_number IS NULL
        ";

        $flag = M()->execute( $sql );
//         $this->w_log( "滞销预警商品_数据添加 {$sql}" );

        return $flag;
    }

    /**
     * 缺货预警_数据添加
     *
     * @param string $start_time 销售开始时间戳(零时区)，包含此时间戳数据;
     * @param string $end_time 销售结束日期时间戳(零时区)，不包含此时间戳数据;
     * @author ^2_3^
     */
    private function goods_shortage_warning_data_add($start_time, $end_time) {
        $flag = false;
        if( empty($start_time) || empty($end_time) ) {
            return $flag;
        }

        $db_prefix = C('DB_PREFIX');
        $sql = "
        -- 缺货预警表_数据添加
        insert into {$db_prefix}goods_shortage_warning(
            goods_id,
            goods_sn,
            goods_name,
            sum_practical_num,
            sum_goods_number,
            begin_time,
            end_time,
            daily_sales_num,
            warning_num,
            record_time
        )
        SELECT
            goods_id,
            goods_sn,
            goods_name,
            sum_practical_num,
            sum_goods_number,
            '{$start_time}' AS begin_time,
            '{$end_time}' AS end_time,
            (sum_goods_number/30) AS daily_sales_num,
            (sum_goods_number/10) AS warning_num,
            (UNIX_TIMESTAMP()-28800) AS record_time
        FROM
        (
            -- 商品所选时段库存销量_数据
            SELECT
                tmp_g.goods_id,
                tmp_g.goods_sn,
                tmp_g.goods_name,
                sum_practical_num,
                sum_goods_number
            FROM
            (
            
                -- 商品库存
                SELECT
                    g.goods_id,
                    g.goods_sn,
                    g.goods_name,
                    SUM(gs.practical_num) AS sum_practical_num
                FROM {$db_prefix}goods g
                LEFT JOIN {$db_prefix}goods_storage gs ON g.goods_id = gs.goods_id
                WHERE g.is_on_sale = 1 AND g.is_delete = 0
                GROUP BY g.goods_id
                
            ) tmp_g
            LEFT JOIN
            (
            
                -- 所选时段销售数量
                SELECT
                    goods_id,
                    goods_sn,
                    goods_name,
                    SUM(sum_goods_number) AS sum_goods_number
                FROM {$db_prefix}goods_day_sales gds
                WHERE gds.pay_date_time >= {$start_time} AND gds.pay_date_time < {$end_time}
                GROUP BY gds.goods_id
                
            ) tmp_s ON tmp_g.goods_id = tmp_s.goods_id
            ORDER BY goods_id
    
        ) tmp_result WHERE sum_practical_num < ((sum_goods_number/30) * 3)
        ";

        $flag = M()->execute( $sql );
//         $this->w_log( "缺货预警_数据添加 {$sql}" );

        return $flag;
    }

    /**
     * 商品日销售表_数据添加
     *
     * @param string $pay_start_time 销售开始时间戳(零时区)，包括此时间戳;
     * @param string $pay_end_time 销售结束时间戳(零时区)，不包括此时间戳;
     * @author ^2_3^
     */
    private function goods_day_sales_data_add($pay_start_time, $pay_end_time) {
        $flag = false;

        if( empty($pay_start_time) || empty($pay_end_time)  ) {
            return $flag;
        }

        $db_prefix = C('DB_PREFIX');
        $sql = "
        insert into {$db_prefix}goods_day_sales(goods_id, goods_sn, goods_name, sum_goods_number, pay_date, pay_date_time)
        select * from
        (
            -- 商品日销售表_数据
            SELECT
                goods_id,
                goods_sn,
                goods_name,
                SUM(goods_number) AS sum_goods_number,
                pay_date,
                pay_date_time
            FROM
            (
                SELECT
                    oi.order_id,
                    oi.order_sn,
                    oi.pay_time,
                    FROM_UNIXTIME(oi.pay_time+28800, '%Y-%m-%d') AS pay_date,
                    UNIX_TIMESTAMP(FROM_UNIXTIME(oi.pay_time+28800, '%Y-%m-%d')) AS pay_date_time,
                    og.goods_id,
                    og.goods_sn,
                    og.goods_name,
                    og.goods_number
                FROM {$db_prefix}order_info oi
                LEFT JOIN {$db_prefix}order_goods og ON oi.order_id = og.order_id
                LEFT JOIN {$db_prefix}users u ON oi.user_id = u.user_id 
                WHERE pay_time >= {$pay_start_time}
                AND pay_time < {$pay_end_time}
                AND u.user_name NOT LIKE 'wx_196%' 
                AND oi.order_status IN (1, 5)
                AND oi.pay_status IN (2, 3)
                AND oi.shipping_status = 2
            ) sell_tmp
            GROUP BY pay_date, goods_id
        ) tmp
        ";
        $flag = M()->execute( $sql );
//         $this->w_log( "商品日销售表_数据添加 {$sql}" );

        return $flag;
    }

    /**
     * 删除日志
     */
    public function del_log(){

        M("alarm_log2")->where('type NOT IN (5)')->delete();
        M("alarm_log2")->where('type = 4 AND state = 1')->delete();

    }


    /**
     *检查库存并检查预约发送信息
     */
    private function check_hook_goods(){

        $booking_goods_array = M("booking_goods")->field("rec_id,tel,goods_id,user_id,goods_name")->where(array("is_dispose"=>0))->select();
        $goods_array = $booking_goods_array['goods_id'];
        $goods_array = array_unique($goods_array);
        if(count($goods_array)>0){
            foreach ($goods_array as $key=>$goods_id){
                $practical_num = M("goods_storage")->where(array("goods_id"=>$goods_id))->getField("practical_num");
                if($practical_num>0){

                    $this->handle_booking($booking_goods_array[$key]['rec_id'],$booking_goods_array[$key]['tel'],$booking_goods_array[$key]['user_id'],$booking_goods_array[$key]['goods_name']);
                }
            }
        }
    }

    /**
     * 修改记录并发送信息
     * @param $rec_id
     * @param $tel
     */
    private function handle_booking($rec_id, $tel,$user_id,$goods_name){
        $data['is_dispose'] = 1;
        $data['dispose_user'] = "系统";
        $data['dispose_time'] = gmtime();
        $data['dispose_note'] = "检测到仓储不为空，自动发送信息给用户";
        M("booking_goods")->where('rec_id='.$rec_id)->save($data);
        $remark['goods_name'] = $goods_name;
        //发送信息给用户
        A("Smsapi")->send_message_api("goods_arrive",$tel,$tel,0,0,0,$user_id,$remark);

    }

    /**
     *检查预警信息
     */
    private function check_alarm(){
        $item_list = M("alarm")->find();

        $no_ready = $item_list['no_ready'];                   //未配货预警时间
        $no_distribution = $item_list['no_distribution'];     //未配送预警时间
        $distribution = $item_list['distribution'];           //未送达预警时间
        $since = $item_list['since'];                         //自提预警时间
        $alarm_interval = $item_list['alarm_interval'];       //预警时间间隔
        $since_cancel = $item_list['since_cancel'];           //自提订单取消时间
        $alarm_presell=$item_list['alarm_presell'];//预售商品缺货预警设置

        $order_info = M('order_info');



        if($no_distribution>0){
            //已开启未配送提醒   同时提醒未出仓
            $where= "quality_id !=0 and order_status !=2 and shipping_status = 5  and outgo = 0 and shipping_id = 3 and sorting_id !=0  and 196_admin_id = 0";   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where(array('type'=>8,'order_sn'=>$value))->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,8);
                        }
                    }else{
                        $this->w_alarm_log($values,8);
                    }
                }
            }
        }
        if($no_distribution>0){
            //已开启未配送提醒   同时提醒未回仓
            $where= "order_status !=2 and outgo = 2 and shipping_id = 3  and 196_admin_id = 0";   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where(array('type'=>9,'order_sn'=>$value))->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,9);
                        }
                    }else{
                        $this->w_alarm_log($values,9);
                    }
                }
            }
        }

        if($no_ready>0){
            //已开启未配货提醒
            $c_time = time()+$no_ready;       //预推时间到
            //已支付且未确认的送货上门订单
            $where= "pay_status in (2,3) and order_status <>2 and shipping_status IN (0,3) and shipping_id = 3 and 196_admin_id = 0";
            $order_sn = $order_info->where($where)->getField('order_sn',true);
            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where(array('type'=>1,'order_sn'=>$value))->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,1);
                        }
                    }else{
                        $this->w_alarm_log($values,1);
                    }
                }
            }
        }


        if($no_distribution>0){
            //已开启未配送提醒
            //dump(gmtime());
            //dump($no_distribution);
            $c_time = gmtime()-$no_distribution;
            //已确认且未发货的送货上门订单
//            $where= "order_info.outgo = 1 and order_info.shipping_status = 5 and order_info.sorting_id <> 0 and order_info.order_status not in (0,2,3,4)
//            and order_info.shipping_id = 3 and deliver_order.add_time <".$c_time ." and order_info.order_id = deliver_order.order_id";  //根据配货时间开始算
//
//            $order_sn =M()->table(array('sdx_order_info'=>'order_info','sdx_warehouse_deliver_order'=>'deliver_order'))
//                ->field('order_info.order_sn')->where($where)->order('id desc')->select();
            $order_sn = M('order_info')->where('196_admin_id = 0 and outgo = 1 and shipping_status = 5 and sorting_id <>0 and order_status <> 2 and shipping_id = 3 and pay_status in(2,3) and sorting_time<'.$c_time)->getField('order_sn',true);
            //dump(M('order_info')->getlastsql());
            //($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where(array('type'=>2,'order_sn'=>$value))->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){

                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,2);
                        }
                    }else{
                        $this->w_alarm_log($values,2);
                    }
                }
            }
        }

        if($distribution>0){
            //已开启未送达提醒
            $c_time = gmtime()-$distribution;
            //已发货的送货上门订单
            $where= "196_admin_id = 0 and shipping_status = 1  and order_status =5 and shipping_id = 3 and shipping_time <> 0 and shipping_time <".$c_time;   //已发货的送货上门订单，超出时间范围
            $order_sn = $order_info->where($where)->getField('order_sn',true);

            //dump($order_info->getlastsql());
            //dump($order_sn);
            if($order_sn){
                foreach ($order_sn as $key=>$value){
                    $up_trigger_time = M("alarm_log2")->where(array('type'=>3,'order_sn'=>$value))->order('id desc')->getField('trigger_time');
                    $values['order_sn'] = $value;
                    if($up_trigger_time){
                        if((time()-$up_trigger_time)>$alarm_interval&&$alarm_interval!=0){
                            $this->w_alarm_log($values,3);
                        }
                    }else{
                        $this->w_alarm_log($values,3);
                    }
                }
            }
        }


        if($since>0){
            //自提预警时间111
            $h = intval(floor($since/3600));
            $m = ($since%3600)/60;
            //if(time()>strtotime(date("y-m-d",time())." ".$h.":".$m.":00")){
            $set_time = $h.":".$m;
            if(date("H:i",time())==$set_time){
                //已达到发送时间

                //已确认且未确认收货的上门自提订单,,,查询今天的数据
                $date_1 = strtotime(date("y-m-d",$this->gmtime())." 00:00:00");
                $date_2 = strtotime(date("y-m-d",$this->gmtime())." 23:59:59");
                $where= "shipping_status <> 2 and order_status = 5 and shipping_id = 2 and (pay_time  between ".$date_1." and ".$date_2.")";
                $order_sn = $order_info->where($where)->select();

//                dump($order_sn);
//                dump($order_info->getlastsql());
//
//                exit();
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $up_trigger_time = M("alarm_log2")->where(array('type'=>4,'order_sn'=>$value['order_sn']))->order('id desc')->getField('trigger_time');
                        if($up_trigger_time){
                            if((time()-$up_trigger_time)>86400){    //一天提醒一次
                                $this->w_alarm_log($value['order_sn'],4);
                                A("Smsapi")->send_message_api("order_remind_new",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                            }
                        }else{
                            $this->w_alarm_log($value['order_sn'],4);
                            A("Smsapi")->send_message_api("order_remind_new",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                        }
                    }
                }
                //已确认且未确认收货的上门自提订单,,,查询昨天的数
                $date_1 = strtotime(date("Y-m-d",$this->gmtime()-86400)." 00:00:00");
                $date_2 = strtotime(date("Y-m-d",$this->gmtime()-86400)." 23:59:59");

                $where= "shipping_status <> 2 and order_status = 5 and shipping_id = 2 and (pay_time  between ".$date_1." and ".$date_2.")";
                $order_sn = M('order_info')->where($where)->select();
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $up_trigger_time = M("alarm_log2")->where(array('type'=>4,'order_sn'=>$value['order_sn']))->order('id desc')->getField('trigger_time');
                        if($up_trigger_time){
                            if((time()-$up_trigger_time)>86400){
                                $this->w_alarm_log($value['order_sn'],4);
                                A("Smsapi")->send_message_api("order_warning",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                            }
                        }else{
                            $this->w_alarm_log($value['order_sn'],4);

                            A("Smsapi")->send_message_api("order_warning",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");
                        }
                    }
                }
            }

            //取消超时订单
            $h = intval(floor($since_cancel/3600));
            $m = ($since_cancel%3600)/60;
            $set_time = $h.":".$m;
            if(date("H:m",time())==$set_time){
                //取消前天的订单
                $date_2 = strtotime(date("Y-m-d",$this->gmtime()-172800)." 23:59:59");
                $where= "order_status in(5,6) and shipping_status = 1 and shipping_id = 2 and pay_time  <".$date_2;
                $order_sn = M('order_info')->where($where)->select();
//                dump(M('order_info')->getlastsql());
//                dump($order_sn);
                if($order_sn){
                    foreach ($order_sn as $key=>$value){
                        $this->w_alarm_log($value['order_sn'],5);
                        //取消订单
                        M('order_info')->where(array("order_id"=>$value['order_id']))->setField('order_status',2);
                        //写入订单取消记录
                        $data['order_id'] = $value['order_id'];
                        $data['action_user'] = '系统';
                        $data['order_status'] = 2;
                        $data['shipping_status'] = $value['shipping_status'];
                        $data['pay_status'] = $value['pay_status'];
                        $data['log_time'] = gmtime();
                        $data['action_note'] = '系统定时任务自动取消';

                        M('order_action')->add($data);

                        $wechat_param=array();

                        switch($_SERVER['SERVER_NAME']){
                            case 'api.xian3.com':
                                $thisurl='xian3.com';
                                break;
                            case 'api.test.shidexian.com':
                                $thisurl='test.shidexian.com';
                                break;
                            case 'api.shidexian.com':
                                $thisurl='w.shidexian.com';
                                break;
                            default:
                                $thisurl='w.shidexian.com';
                                break;
                        }
                        $oid=$list['user_id'];
                        $Code=md5($oid.'sdx@9999');

                        $goods_name=M("order_goods")->where(array('order_id'=>$value['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$value['order_id'].')')))->limit(1)->getField("goods_name");
                        $goods_number=M("order_goods")->where(array('order_id'=>$value['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$value['order_id'].')')))->count();

                        $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($list['order_id']);

                        $housekeeper='';
                        if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                            $housekeeper="任何订单问题可在微信中添加您的专属客服楼管家".$louxiaoer_info['name']."-".$louxiaoer_info['phone']."咨询，还能最高返现8元哦。祝生活愉快！";
                        }else{
                            $housekeeper="联系楼管家还能再返现。如需添加，请于微信公众号留言。";
                        }

                        $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHddqx";
                        $wechat_param['first']='尊敬的'.$value['consignee'].'，退款将在1-3个工作日内退回您的账户，请注意查收，欢迎再次光临食得鲜。';
                        $wechat_param['orderProductPrice']=sprintf("%.2f",($value['order_amount']+$value['money_paid']+$value['surplus']));
                        $wechat_param['orderProductName']=$goods_name.'等'.$goods_number.'件';
                        $wechat_param['orderAddress']=$value['address'];
                        $wechat_param['orderName']=$value['order_sn'];
                        $wechat_param['remark']=$housekeeper;

                        //dump("已取消订单:".$value['order_sn']);
                        A("Smsapi")->send_message_api("order_cancel",$value['mobile'],$value['consignee'],0,$value['order_sn'],0,$value['user_id'],null,"22:00");

                    }
                }
            }


            //清空未处理订单的记录
            if(date("H:m",time())=="23:55"){
                M('alarm_log2')->where(array("type"=>5,"state"=>0))->delete();
            }

        }

        if($alarm_presell>0){
            //
            $h = intval(floor($alarm_presell/3600));
            $m = ($alarm_presell%3600)/60;
            if($m==0){
                $m='00';
            }
            $time=time();
            $set_date_ymd=date('Y-m-d',$time);
            $set_time = $set_date_ymd.$h.":".$m;
            $set_time = strtotime($set_time);
            if($time >= $set_time){
                $is_presell_sql='SELECT * FROM(SELECT oi.order_id,oi.order_sn FROM '.C('DB_PREFIX').'order_info as oi'.
                    ' LEFT JOIN  '.C('DB_PREFIX').'order_goods as og ON og.order_id=oi.order_id'.
                    ' WHERE og.is_presell=1 AND og.buckle_inventory=0 AND (oi.pay_status IN (2,3)) AND oi.pay_status!=4 AND oi.shipping_status =0'.
                    " AND (oi.order_status NOT IN (0,2,3,4)) AND oi.best_time < UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 23:59:59'))".
                    ' ) as t'.
                    ' GROUP BY order_id';
                $order_info=M()->query($is_presell_sql);
                if($order_info){
                    foreach ($order_info as $key=>$val){
                        if($this->check_yujing_distinct($val['order_sn'],7)){
                            $values['order_sn'] = $val['order_sn'];
                            $this->w_alarm_log($values,7);
                        }
                    }
                }
            }
        }
    }

    /**
     * 插入问题单预警日志
     * Created by Jerry
     */
    private function check_alarm_type_wrong()
    {
        $sql = "SELECT o.order_sn, a.action_type FROM sdx_order_action as a 
                LEFT JOIN sdx_order_goods AS g ON a.order_id = g.order_id 
                LEFT JOIN sdx_order_info AS o ON o.order_id = a.order_id
                LEFT JOIN sdx_alarm_log2 as al ON al.order_sn = o.order_sn
                WHERE 
                a.action_type = 6
                AND 
                o.shipping_status != 2
                AND
                al.order_sn IS NOT NULL
                AND 
                o.shipping_status != 3
                AND 
                o.order_status != 2
                GROUP BY o.order_sn";

        $model = M();

        $rs = $model->query($sql);

        foreach ($rs  as $k => $v){
            $this->w_alarm_log($v, $v['action_type']);
        }
    }

    /**
     * 自提单预警插入
     * Created by Jerry
     */
    private function check_alarm_type_4()
    {
        $sql = "SELECT o.order_sn, 4 as type FROM sdx_order_info as o 
                LEFT JOIN
                sdx_alarm_log2 AS a
                ON
                (o.order_sn = a.order_sn)
                WHERE
                a.order_sn IS NULL
                AND 
                o.`shipping_id` = 2
                AND
                o.order_status != 2
                AND 
                o.pay_status = 2
                AND
                (
                o.shipping_status = 1
                OR 
                o.shipping_status = 0
                )
                GROUP BY o.order_sn";

        $model = M();

        $rs = $model->query($sql);

        foreach ($rs  as $k => $v){
            $this->w_alarm_log($v, $v['type']);
        }
    }

    /*
     * 根据预警日志去重
     * */
    private function check_yujing_distinct($order_sn,$type){
        $id=M('alarm_log2')->where(array('order_sn'=>$order_sn,'type'=>$type,'state'=>0))->getField('id');
        if($id>0){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 写入警告记录
     * @param $order_sn
     * @param $type
     */
    private function w_alarm_log($value, $type){
        $in_data['order_sn'] = $value['order_sn'];
        $in_data['type'] = $type;
        $in_data['trigger_time'] = time();
        $in_data['state'] = 0;
        M('alarm_log2')->add($in_data);
    }


    private function w_operate_log($goods_sn,$goods_id,$goods_name,$type){
        $in_data['goods_sn'] = $goods_sn;
        $in_data['goods_id'] = $goods_id;
        $in_data['goods_name'] = $goods_name;
        $in_data['type'] = $type;
        M('operate_log')->add($in_data);
    }

    public function operate_goods_weight(){
        //
        M('operate_log')->where(array("type"=>100))->delete();
        $goods_list = M("goods")->where('goods_weight >= 10 and is_delete = 0')->field('goods_weight,goods_id,goods_sn,goods_name')->select();
        //dump($goods_list);
        foreach ($goods_list as $key=>$value){
            if(M("operate_log")->where(array("goods_id"=>$value['goods_id']))->field("goods_id")->count()==0){
                $in_data['goods_sn'] = $value['goods_sn'];
                $in_data['goods_id'] = $value['goods_id'];
                $in_data['goods_name'] = $value['goods_name'];
                $in_data['goods_weight'] = $value['goods_weight'];
                $in_data['type'] = 100;
                M('operate_log')->add($in_data);
            }
        }
    }

    private function operate_goods(){

        $model = M();

        //未上架有库存
//        $goods_list = M("goods")->where('is_on_sale = 0')->field('goods_id,goods_sn,goods_name')->select();
//        foreach ($goods_list as $key=>$value){
//            $practical_num = M("goods_storage")->where('goods_id = '.$value['goods_id'])->SUM('practical_num');
//            //dump($practical_num."---".M("goods_storage")->getlastsql());
//            if($practical_num>0){
//                $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],1);
//            }
//        }

        $sql = "SELECT
	gd.goods_id,gd.goods_sn,gd.goods_name
FROM
	sdx_goods AS gd
WHERE
	(
		SELECT
			SUM(gs.practical_num)
		FROM
			sdx_goods_storage AS gs
		WHERE
			gd.goods_id = gs.goods_id
	) > 0
AND gd.is_on_sale = 0 AND gd.is_delete = 0";


        $goods_list = $model->query($sql);


        M("operate_log")->where('type = 1')->delete();

        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],1);
        }




        //无库存已上架

        $sql = "SELECT
	gd.goods_id,gd.goods_sn,gd.goods_name
FROM
	sdx_goods AS gd
WHERE
	(
		SELECT
			SUM(gs.practical_num)
		FROM
			sdx_goods_storage AS gs
		WHERE
			gd.goods_id = gs.goods_id
	) = 0
AND gd.is_on_sale = 1 AND gd.is_delete = 0";

        $goods_list = $model->query($sql);
        M("operate_log")->where('type = 2')->delete();
        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],2);
        }

//
//
//
//
//        $goods_list = M("goods")->where('is_on_sale = 1')->field('goods_id,goods_sn,goods_name')->select();
//        foreach ($goods_list as $key=>$value){
//            $practical_num = M("goods_storage")->where('goods_id = '.$value['goods_id'])->SUM('practical_num');
//            if($practical_num==0){
//                //dump($practical_num."---".M("goods_storage")->getlastsql());
//                $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],2);
//            }
//        }
        //无图片已上架
        $goods_list = M("goods")->where('is_on_sale = 1 AND goods_thumb =""  AND is_delete = 0')->field('goods_id,goods_sn,goods_name')->select();
        //dump($goods_list."---".M("goods")->getlastsql());
        M("operate_log")->where('type =3')->delete();
        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],3);
        }

//        有图片未上架
        $goods_list = M("goods")->where('is_on_sale = 0 AND goods_thumb !=""  AND is_delete = 0')->field('goods_id,goods_sn,goods_name')->select();
        //dump($goods_list."---".M("goods")->getlastsql());
        M("operate_log")->where('type = 10')->delete();
        foreach ($goods_list as $key=>$value){
            $this->w_operate_log($value['goods_sn'],$value['goods_id'],$value['goods_name'],10);
        }
    }

    /**
     * 显示领取过登录奖励  且今天没有登录过的用户的手机号码，如果未绑定手机号 则读取收货地址中的手机号码
     */
    public function show_unlogin(){
        $i=0;
        $is_give = M("user_action")->where("TO_DAYS(from_unixtime(action_time)) != TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND action_type='登录奖励'")->getField("user_id",true);
        $old_give_array = array_unique($is_give);
        //dump($old_give_array);
        foreach ($old_give_array as $value){
            //查询此用户今天是否送过钱 全部为昨天登录过的
            $now_unlogin = M("user_behavior_address")->where("type = 'login' AND uid = {$value} AND TO_DAYS(from_unixtime(add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800))")->count();
            if(empty($now_unlogin)){
                $i ++;
                $now_moeny = M("users")->where(array("user_id"=>$value))->field("mobile_phone")->find();
                if($now_moeny['mobile_phone']){
                    //是绑定手机号
                    w_log("ddd",$now_moeny['mobile_phone']);
                }else{
                    //未绑定手机号/查询默认地址中的手机号
                    $give_phone = M("user_address")->where(array("user_id"=>$value,"default"=>1))->getField("mobile");
                    if(empty($give_phone)){
                        $give_phone = M("user_address")->where("user_id = {$value} and mobile!=''")->getField("mobile");
                    }
                    if(empty($give_phone)){
                        w_log("ddd", M("user_address")->getLastSql());
                    }else{
                        w_log("ddd",$give_phone);
                    }

                }
            }
        }
        dump($i);
    }

    private function get_wechat_param($uid){
        $wechat_param['url']="https://w.shidexian.com/?index#/index?utm_source=GZHtxsx";
        $wechat_param['first']='回食得鲜商城来看看吧，签到送钱活动持续进行中哦！';
        $wecnickname=M("wechat_user")->where(array("ect_uid"=>$uid))->getField("nickname");
        $wechat_param['keyword1']=$wecnickname;
        $jladd_time=M("user_account")->where(array("user_id"=>$uid,"admin_note"=>array("like","登录奖励%"),"is_paid"=>1))->order("add_time desc")->getField("add_time");
        $wechat_param['keyword2']=gmdate("Y-m-d",$jladd_time);
        $jlamount=M("user_account")->where(array("user_id"=>$uid,"admin_note"=>array("like","登录奖励%"),"is_paid"=>1))->sum("amount");
        $wechat_param['keyword3']='累积奖励'.$jlamount;
        $jlcount=M("user_account")->where(array("user_id"=>$uid,"admin_note"=>array("like","登录奖励%"),"is_paid"=>1))->count();
        $wechat_param['keyword4']='累积签到'.$jlcount.'次';

        return $wechat_param;
    }

    /**
     * 领取过登录奖励，但是最近没有上线，则短信提醒  短信提醒频率为3天一次
     */
    public function urge_online(){
        exit("已停止此活动");
        set_time_limit(0);
        if(date("H:i")!="16:00"){
            //exit("运行时间错误");
        }
        $i=0;

        dump(local_date("Y-m-d H:i:s",gmtime()));



        $msg_opt = M("mail_templates")->where(array("template_code"=>"urge_online"))->getField("msg_opt");
        $msg_opt = str_replace("\r\n",",",$msg_opt);
        $msg_opt = explode(",",$msg_opt);
        $is_give = M("account_log")->where("change_type = 8")->field("user_id,max(change_time) AS change_time")->order("change_time desc")->group("user_id")->select();

        $wechat_param=$this->get_wechat_param(1980);
        A("Smsapi")->send_message_api("urge_online",15820245055,'促进上线',0,0,0,1980,array("goods_title"=>$msg_opt[0]),null,$wechat_param);

        $wechat_param=$this->get_wechat_param(448);
        A("Smsapi")->send_message_api("urge_online",18620277922,'促进上线',0,0,0,448,array("goods_title"=>$msg_opt[0]),null,$wechat_param);

        $wechat_param=$this->get_wechat_param(4228);
        A("Smsapi")->send_message_api("urge_online",13760817463,'促进上线',0,0,0,4228,array("goods_title"=>$msg_opt[0]),null,$wechat_param);


        $i = 0;
        $new_array =array();

        $phone_array =array();
        foreach ($is_give as $key=>$value){
            $date=floor((gmtime()-$value['change_time'])/86400);    //已经未发奖励
            if($date>0 &&$date%3==0){
                $num = M("message_log")->where("user_id = {$value['user_id']} AND templates_id = 54 AND TO_DAYS(send_time) = TO_DAYS(NOW())")->count();
                if($num==0){
                    $new_array[] = $value['user_id'];
                    $now_phone = M("users")->where(array("user_id"=>$value['user_id']))->getField("mobile_phone");
                    if($now_phone){
                        //是绑定手机号
                        //dump(local_date("Y-m-d H:i:s",$value['change_time']));
                        dump($value['user_id']);
                        $phone_array[] = $now_phone;

                        $wechat_param=$this->get_wechat_param($value['user_id']);
                        $sms_r = A("Smsapi")->send_message_api("urge_online",$now_phone,'促进上线',0,0,0,$value['user_id'],array("goods_title"=>$msg_opt[0]),null,$wechat_param);
                    }else{
                        //未绑定手机号/查询默认地址中的手机号
                        $give_phone = M("user_address")->where(array("user_id"=>$value['user_id'],"default"=>1))->getField("mobile");
                        if(empty($give_phone)){
                            $give_phone = M("user_address")->where("user_id = {$value['user_id']} and mobile!=''")->getField("mobile");
                        }
                        if($give_phone){
                            //dump(local_date("Y-m-d H:i:s",$value['change_time']));
                            dump($value['user_id']);
                            $phone_array[] = $give_phone;

                            $wechat_param=$this->get_wechat_param($value['user_id']);

                            $sms_r = A("Smsapi")->send_message_api("urge_online",$give_phone,'促进上线',0,0,0,$value['user_id'],array("goods_title"=>$msg_opt[0]),null,$wechat_param);
                        }
                    }
                }
            }
        }
    }


    /**
     * 显示以前登录过，未领取过登录奖励的用户
     */
    public function show_unline(){
        exit("已停止此活动");
        set_time_limit(0);
        $now_unlogin = M("user_behavior_address")->where("type = 'login'")->group("uid")->getField("uid",true);
        foreach ($now_unlogin as $key=>$value){
            $is_give = M("user_action")->where("action_type='登录奖励' AND user_id=".$value)->count();
            if($is_give>0){
                unset($now_unlogin[$key]);
            }else{
                $now_phone = M("users")->where(array("user_id"=>$value))->getField("mobile_phone");
                if($now_phone){
                    //是绑定手机号
                    echo $now_phone."<br/>";
                }else{
                    //未绑定手机号/查询默认地址中的手机号
                    $give_phone = M("user_address")->where(array("user_id"=>$value,"default"=>1))->getField("mobile");
                    if($give_phone){
                        echo $give_phone."<br/>";
                    }
                }
            }
        }
    }

    private function get_daily_rewards_wechat_param($phone,$key){
        $wechat_param['url']="https://w.shidexian.com/?index#/index?utm_source=GZHmrjl";
        $wechat_param['first']='尊敬的小主，您昨日的登录福利已发放，请注意查收~每天登录每天送。';
        $wechat_param['keyword1']=$phone;
        $wechat_param['keyword2']=date("Y-m-d",strtotime("-1 day"));
        $wechat_param['keyword3']='1元';
        $jlamount=M("user_account")->where(array("user_id"=>$key,"admin_note"=>array("like","登录奖励%"),"is_paid"=>1))->sum("amount");
        $wechat_param['keyword4']='签到已累计奖励'.$jlamount.'元';
        return $wechat_param;
    }

    /**
     * 今天第一次领取奖励的用户发送信息
     */
    private function auto_give_money_msg(){
        exit("已停止此活动");
        set_time_limit(0);
        $give_phone = array();

        $i=0;
        $give_list = M("account_log")->where("change_type = 8 AND TO_DAYS(from_unixtime(change_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800))")
            ->getField("user_id",true);
        //今天已经登录
        foreach ($give_list as $key=>$value){
            $give_num = M("account_log")->where("change_type = 8 AND user_id=".$value)->count();
            if($give_num==1){
                //发送信息
                $mobile_phone = M("users")->where(array("user_id"=>$value))->getField("mobile_phone");
                if($mobile_phone){
                    //是绑定手机号
                    $give_phone[$value] = $mobile_phone;
                }else{
                    //未绑定手机号/查询默认地址中的手机号
                    $give_phone[$value] = M("user_address")->where(array("user_id"=>$value,"default"=>1))->getField("mobile");
                }
                $i++;
            }

        }
        $give_phone = array_unique(array_filter($give_phone));
        $msg_opt = M("mail_templates")->where(array("template_code"=>"daily_rewards"))->getField("msg_opt");

        $msg_opt = str_replace("\r\n",",",$msg_opt);
        $msg_opt = explode(",",$msg_opt);

        foreach ($give_phone as $key=>$phone){
            //发送信息到用户手机
            //echo "手机:".$value."</br>";

            $wechat_param=$this->get_daily_rewards_wechat_param($phone,$key);

            A("Smsapi")->send_message_api("daily_rewards",$phone,$msg_opt[0],0,0,0,$key,array("goods_title"=>$msg_opt[1]),null,$wechat_param);
        }

        $wechat_param=$this->get_daily_rewards_wechat_param(15820245055,1980);
        A("Smsapi")->send_message_api("daily_rewards",15820245055,$msg_opt[0],0,0,0,1980,array("goods_title"=>$msg_opt[1]),null,$wechat_param);

        $wechat_param=$this->get_daily_rewards_wechat_param(18620277922,448);
        A("Smsapi")->send_message_api("daily_rewards",18620277922,$msg_opt[0],0,0,0,448,array("goods_title"=>$msg_opt[1]),null,$wechat_param);

        $wechat_param=$this->get_daily_rewards_wechat_param(13760817463,4228);
        A("Smsapi")->send_message_api("daily_rewards",13760817463,$msg_opt[0],0,0,0,4228,array("goods_title"=>$msg_opt[1]),null,$wechat_param);
    }

    /**
     * 送一元钱
     */
    public function auto_give_money(){
        exit("已停止此活动");
        set_time_limit(0);
        $auto_cache = S("auto_give_money");
        if($auto_cache){
            return false;
        }else{
            S("auto_give_money",1,600);
        }
        if(gmtime()>1490975999){
            exit("活动已结束，请停止运行 auto_give_money");
        }
        //if(date("H")!=8&&date("i")!=30){
        exit("运行时间错误");
        //}
        //查询昨天有浏览记录绑定手机用户
        $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();
        //dump(M()->getLastSql());
        $give_address = array();
        foreach ($yesterday_address as $value){
            $give_address[] = $value['uid'];
        }


        //查询昨天有登录标记绑定手机用户
        $yesterday_address_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();
        //dump(M()->getLastSql());
        $give_address_login = array();
        foreach ($yesterday_address_login as $value){
            $give_address_login[] = $value['uid'];
        }

        //dump($yesterday_address);
        //查询昨天有登录标记地址中有手机用户
        $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login_login = array();
        foreach ($yesterday_login_login as $value){
            $give_login_login[] = $value['uid'];
        }
        //dump($yesterday_address);
        //查询有浏览商品记录浏览商品记录
        $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login = array();
        foreach ($yesterday_login as $value){
            $give_login[] = $value['uid'];
        }
        //dump($yesterday_login);
        $old_give_array = array_unique(array_merge($give_login,$give_address,$give_login_login,$give_address_login));

//        dump($old_give_array);
//        exit();
        $array_give = array();
        foreach ($old_give_array as $value){
            //查询此用户今天是否送过钱
            $is_give = M("account_log")->where("TO_DAYS(from_unixtime(change_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND change_type = 8 AND user_id=".$value)->field("log_id")->count();

            if($is_give==0) {
                $array_give[] =$value;
            }
        }
        $array_give = array_unique($array_give);
        if(count($array_give)>0){
//            dump($array_give);
//            exit();
            $to_user_money = $this->users_money($array_give);
            if($to_user_money){
                //$this->update_users_money();
                $this->auto_give_money_msg();   //第一次领取奖励用户发送短信
            }

        }
    }


    private function users_money($array_give){
        exit("已停止此活动");
        $new_array =array();
        if(!empty($array_give)){
            $array_give = array_unique($array_give);
            foreach ($array_give as $key=>$value){
                $is_give = M("account_log")->where("TO_DAYS(from_unixtime(change_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND change_type = 8 AND user_id=".$value)->field("log_id")->count();
                if($is_give==0) {
                    $new_array[$key] = $value;

                    $user_a_data[] = array(
                        "amount" => 1,
                        "is_paid" => 1,
                        "process_type" => 7,
                        "add_time" => gmtime(),
                        "user_note" => "登录奖励 [ ".date("Y-m-d",strtotime("-1 day"))." ]",
                        "admin_note" => "登录奖励 [ ".date("Y-m-d",strtotime("-1 day"))." ]",
                        "user_id" => $value,
                    );

                    $user_al_data[] =  array(
                        "user_money" => 1.00,
                        "change_type" => 8,
                        "pay_points" => 0,
                        "rank_points" => 0,
                        "action_user" => "赠送脚本",
                        "frozen_money" => 0.00,
                        "change_time" =>  gmtime(),
                        "user_id" =>  $value,
                        "change_desc" => "登录奖励 [ ".date("Y-m-d",strtotime("-1 day"))." ]"
                    );

                    $dataList[] = array(
                        'user_id'=>$value,
                        'money'=>1.00,
                        'type'=>2,  //登录奖励送
                        'add_time'=>gmtime()
                    );
                    $now_moeny = M("users")->where(array("user_id" => $value))->field("user_money")->find();


                    $user_action_data[] = array(
                        "action_name" => "System",
                        "action_time" => gmtime(),
                        "action_type" => "登录奖励 [ ".date("Y-m-d",strtotime("-1 day"))." ]",
                        "user_id" => $value,
                        "old_value" => $now_moeny['user_money'],
                        "new_value" => $now_moeny['user_money'] + 1,
                    );
                }
            }
            $new_array_user_id = array_unique($new_array);
            M()->execute("UPDATE sdx_users SET user_money=user_money + 1 WHERE user_id IN (".implode(",",$new_array_user_id).")");
            M("account_log")->addAll($user_al_data);
            M("user_action")->addAll($user_action_data);
            M("user_account")->addAll($user_a_data);
            M("gift_gct")->addAll($dataList);
            //echo "UPDATE sdx_users SET user_money=user_money + 1 WHERE user_id IN (".implode(",",$new_array_user_id).")";
            return true;
        }else{
            return false;
        }
    }



    /**
     * 账户预警 查询出用户余额与用户账户操作记录不符合的记录
     * poptser@foxmail.com
     */
    public function check_users_money(){
        set_time_limit(0);
        M("alarm_account")->where(array("type"=>17))->delete();
        $users_data = M("users")->field("user_id,user_money,mobile_phone,user_name")->where("mobile_phone !=''")->select();
        foreach ($users_data as $key=>$value){
            $user_access = M("account_log")->where(array("user_id"=>$value['user_id']))->sum('user_money');

            if(empty($user_access)){
                $user_access = 0.00;
            }

            if($user_access!=$value['user_money']){

                $dataList[] = array(
                    'user_name'=>$value['user_name'],
                    'phone'=>$value['mobile_phone'],
                    'type'=>17,
                    'now'=>$value['user_money'],
                    'ctime'=>gmtime(),
                    'old'=>$user_access,
                    'user_id'=>$value['user_id']
                );

            }
        }
        M("alarm_account")->addAll($dataList);
    }

    /**
     * 用于检查出账户中钱送错了，并修改记录
     */
    private function update_users_money(){
        exit("已停止此活动");
        $i=0;
        $user_array = array();
        $is_give = M("account_log")->where("TO_DAYS(from_unixtime(change_time+28800)) = TO_DAYS(now()) AND change_type=8")->getField("user_id",true);
        foreach ($is_give as $value){
            $now = M("account_log")->where("TO_DAYS(from_unixtime(change_time+28800)) = TO_DAYS(now()) AND change_type=8 AND user_id ={$value}")->count();
            if($now>1){
                //dump($value);
                $user_array[] = $value;
                $i++;
            }
        }
        $new_array = array_unique($user_array);
        if(count($new_array)>0){
            //dump($new_array);
            $where['user_id'] = array("in",$new_array);
            M("users")->where($where)->setDec("user_money");
            $action_array = array();
            foreach ($new_array as $value){
                $now = M("user_action")->where("TO_DAYS(from_unixtime(action_time+28800)) = TO_DAYS(now()) AND action_type LIKE '登录奖励%' AND user_id ={$value}")->order("id DESC")->getField("id");

                $action_array[] = $now;

            }
            $where['id'] = array("in",array_unique($action_array));
            M("user_action")->where($where)->delete();
//
            $account_array = array();
            foreach ($new_array as $value){
                $now = M("account_log")->where("TO_DAYS(from_unixtime(change_time+28800)) = TO_DAYS(now()) AND change_desc LIKE '登录奖励%' AND user_id ={$value}")->order("change_time DESC")->getField("log_id");

                $account_array[] = $now;

            }
            //dump($account_array);
            $where['log_id'] = array("in",array_unique($account_array));
            M("account_log")->where($where)->delete();

            $user_account_array = array();
            foreach ($new_array as $value){
                $now = M("user_account")->where("TO_DAYS(from_unixtime(add_time+28800)) = TO_DAYS(now()) AND admin_note LIKE '登录奖励%' AND user_id ={$value}")->order("add_time DESC")->getField("id");

                $user_account_array[] = $now;

            }


            $where['id'] = array("in",array_unique($user_account_array));
            M("user_account")->where($where)->delete();
        }

    }

    /**
     * 测试
     */
    public function test(){
        set_time_limit(0);
        M("alarm_account")->where(array("type"=>17))->delete();
        $users_data = M("users")->field("user_id,user_money,mobile_phone,user_name")->where("mobile_phone !=''")->select();
        foreach ($users_data as $key=>$value){
            $user_access = M("account_log")->where(array("user_id"=>$value['user_id']))->sum('user_money');

            if(empty($user_access)){
                $user_access = 0.00;
            }

            if($user_access-$value['user_money']==1){

                echo $value['user_id'].",";

            }
        }
    }

    /**
     * 分享新用户绑定手机号送钱活动
     */
    public function check_user_share(){
        exit("已停止此活动");
        set_time_limit(0);
        //header("Content-type: text/html; charset=utf-8");
        if(gmtime()>1490975999){
            //exit("活动已结束，请停止运行 auto_give_money");
        }
        if(date("H")!=8&&date("i")!=30){
            exit("运行时间错误");
        }
        //所有应该送的
        $all_share_user = M("user_behavior_address")->where(array("is_first_login"=>1,"share_uid"=>array("neq",0)))->getField("uid",true);

        $all_share_user = array_unique($all_share_user);



        $complete_user = M("gift_gct")->where(array("type"=>1))->getField("user_id",true);    //所有已经送过的用户
        if(empty($complete_user)){
            $Need_user = $all_share_user;
        }else{
            $Need_user = array_diff($all_share_user,$complete_user);
        }


        $today_user = array();
        foreach ($Need_user as $key=>$value){
            //今天需要送钱的用户
            $share_user = M("user_behavior_address")->where(array("is_first_login"=>1,"uid"=>$value))->find();
            //查询被邀请用户与邀请者是否绑定手机号码
            $phone_user = M("users")->where(array("user_id"=>$share_user['uid']))->getField("mobile_phone");
            $phone_user_launch = M("users")->where(array("user_id"=>$share_user['share_uid']))->getField("mobile_phone");


            if(!empty($phone_user)&&!empty($phone_user_launch)){
                //双方绑定手机均不为空，为发起者送一元


                $add_m = M("users")->where(array("user_id" => $share_user['share_uid']))->setInc('user_money');   //用户金额+1
                if ($add_m) {
                    $today_user[] = array(
                        $phone_user,$phone_user_launch,$share_user['share_uid']
                    );
                    $dataList[] = array(
                        'user_id'=>$value,
                        'money'=>1.00,
                        'type'=>1,  //分享赠送金额
                        'add_time'=>gmtime()
                    );

                    //新增钱成功，写入账户记录，写入用户余额变动记录
                    $now_moeny = M("users")->where(array("user_id" => $share_user['share_uid']))->field("user_money,mobile_phone")->find();
                    $user_a_data['admin_user'] = $user_action_data['action_name'] = "System";
                    $user_al_data['change_time'] = $user_a_data['add_time'] = $user_a_data['add_time'] = $user_action_data['action_time'] = gmtime();
                    $user_al_data['change_desc'] = $user_a_data['user_note'] = $user_a_data['admin_note'] = $user_action_data['action_type'] = "邀请用户 [ ".$phone_user." ] 奖励";
                    $user_action_data['old_value'] = $now_moeny['user_money'] - 1;
                    $user_al_data['user_id'] = $user_a_data['user_id'] = $user_action_data['user_id'] = $share_user['share_uid'];
                    $user_action_data['new_value'] = $now_moeny['user_money'];
                    $is = M("user_action")->add($user_action_data);
                    //dump("user_action:".M("user_action")->getlastsql());

                    $user_a_data['amount'] = 1;
                    $user_a_data['is_paid'] = 1;
                    $user_a_data['process_type'] = 7;
                    $is =M("user_account")->add($user_a_data);
                    //dump("user_account:".M("user_account")->getlastsql());
                    $user_al_data['user_money'] = 1.00;
                    $user_al_data['change_type'] = 0;
                    $user_al_data['pay_points'] = 0;
                    $user_al_data['rank_points'] = 0;
                    $user_al_data['frozen_money'] = 0.00;
                    $user_al_data['action_user'] = "赠送脚本";
                    $is =M("account_log")->add($user_al_data);
                    //dump("account_log:".M("account_log")->getlastsql());
                }
            }
        }
        if(!empty($dataList)){
            M("gift_gct")->addAll($dataList);
        }

        foreach ($today_user as $value){
            $phone_user_nickname = M("wechat_user")->where(array("ect_uid"=>$value[2]))->getField("nickname");
            $phone_user_mobile = M("users")->where(array("user_id"=>$value[2]))->getField("mobile_phone");

            $wechat_param['url']="https://w.shidexian.com/?index&utm_source=GZHddqx";
            $wechat_param['first']='呼朋引伴，签到拿钱！您已成功邀请一位好友来食得鲜签到。';
            $wechat_param['keyword1']=$phone_user_nickname;
            $wechat_param['keyword2']=$phone_user_mobile;
            $wechat_param['keyword3']=date("Y-m-d");
            $wechat_param['remark']='邀请奖励1元钱已发至您在食得鲜的账户余额，请查收！您每天登陆也有1元钱喔';

            A("Smsapi")->send_message_api("share_rewards",$value[1],$value[0],0,0,0,$value[2],array(),null,$wechat_param);
        }
    }

    public function update_goods_wid_info(){
        $goods_info = M("goods_wid_8")->field("goods_id,is_on_sale,warn_number,goods_number")->select();
        $goods_model = M("goods");
        foreach ($goods_info as $key=>$value){
            $save['is_on_sale'] = $value['is_on_sale'];
            $save['warn_number'] = $value['warn_number'];
            $save['goods_number'] = $value['goods_number'];
            $goods_model->where(array("goods_id"=>$value['goods_id']))->save($save);
        }
    }



    /**
     * 检测过期红包提醒
     */
    public function check_bonus_expired_count(){
        ini_set('max_execution_time', '0');
        set_time_limit(0);

        $enum=I("get.enum");
        $where='';
        if($enum!=''){
            $where=' and ub.bonus_id % 50 = '.$enum;
        }

        $Model = new Model();
        $bonus_list=$Model->query("select count(DISTINCT u.user_id) as count from sdx_user_bonus as ub left join sdx_bonus_type as bt on ub.bonus_type_id=bt.type_id left join sdx_users as u on u.user_id=ub.user_id left join sdx_wechat_user as wu on wu.ect_uid=u.user_id where ((bt.use_end_date > ".local_strtotime(local_date("Y-m-d",local_strtotime("+0 days")))." and bt.use_end_date<".local_strtotime(local_date("Y-m-d",local_strtotime("+1 days"))).") or (ub.deadline > (".local_strtotime(local_date("Y-m-d",local_strtotime("+0 days"))).") and ub.deadline < (".local_strtotime(local_date("Y-m-d",local_strtotime("+1 days"))).") and bt.has_effective_days=1)) and ub.used_time=0 and ub.user_id>0 and u.platform=0 and u.user_name not like 'wx_196%' ".$where." and ub.is_notice in(0,1) group by ub.user_id");

        dump($bonus_list);


    }

    /**
     * 检测过期红包提醒
     */
    public function check_bonus_expired(){
        exit();
        ini_set('max_execution_time', '0');
        set_time_limit(0);


        $enum=I("get.enum");
        $where='';
        if($enum!=''){
            $where=' and ub.bonus_id % 50 = '.$enum;
        }

        $is_notice=true;
        do{

            $Model = new Model();
            $bonus_list=$Model->query("select wu.nickname,bt.type_name,group_concat(bt.bonus_discount_type) as bonus_discount_type_str,bt.type_money,group_concat(bt.type_money) as type_money_str,bt.min_goods_amount,group_concat(bt.min_goods_amount) as min_goods_amount_str,bt.use_end_date,ub.bonus_sn,group_concat(ub.bonus_id) as bonus_id,ub.deadline,u.user_name,u.mobile_phone,u.user_id from sdx_user_bonus as ub left join sdx_bonus_type as bt on ub.bonus_type_id=bt.type_id left join sdx_users as u on u.user_id=ub.user_id left join sdx_wechat_user as wu on wu.ect_uid=u.user_id where ((bt.use_end_date > ".local_strtotime(local_date("Y-m-d",local_strtotime("+2 days")))." and bt.use_end_date<".local_strtotime(local_date("Y-m-d",local_strtotime("+3 days"))).") and ub.deadline=0 or (ub.deadline > (".local_strtotime(local_date("Y-m-d",local_strtotime("+2 days"))).") and ub.deadline < (".local_strtotime(local_date("Y-m-d",local_strtotime("+3 days"))).") and bt.has_effective_days=1)) and ub.used_time=0 and ub.user_id>0 and ub.is_notice=0 and u.platform=0 and u.user_name not like 'wx_196%' ".$where." group by ub.user_id limit 600");



            if(count($bonus_list)==0){
                $is_notice=false;
            }

            $bonus_id_arr=array(0);

            foreach($bonus_list as $item){

                //echo $item['user_name'].' -- '.$item['type_name'].' -- '.local_date("Y-m-d",$item['use_end_date']).'<br>';
                $nickname='食得鲜用户';

                if(!empty($item['nickname'])){
                    $nickname=$item['nickname'];
                }

                if($item['deadline']!=0){
                    $user_use_end_date=local_date("Y-m-d",$item['deadline']);
                }else{
                    $user_use_end_date=local_date("Y-m-d",$item['use_end_date']);
                }

                $betweenSecond=strtotime($user_use_end_date)-strtotime(date("Y-m-d"));
                $dayS=$betweenSecond/(24*60*60);
                $dayS+=1;

                $bonus_discount_type_arr=explode(",",$item['bonus_discount_type_str']);
                $min_goods_amount_arr=explode(",",$item['min_goods_amount_str']);
                $type_money_arr=explode(",",$item['type_money_str']);


                $keyword1='';
                $bonus_amount=0;

                $bonusqqq=array('min_goods_amount'=>0,'type_money'=>0);

                foreach($bonus_discount_type_arr as $key=>$val){
                    if($val==1){
                        $keyword1.='满'.$min_goods_amount_arr[$key].'减'.$type_money_arr[$key].'红包 ';
                        $bonus_amount+=$type_money_arr[$key];
                        if($type_money_arr[$key]>$bonusqqq['type_money']){
                            $bonusqqq['min_goods_amount']=$min_goods_amount_arr[$key];
                            $bonusqqq['type_money']=$type_money_arr[$key];
                        }
                    }elseif($val==2){
                        $keyword1.=$type_money_arr[$key].'折红包 ';
                    }
                }





                $wechat_param['url']="https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder";
                $wechat_param['first']='陪你那么久，不想留遗憾！';
                $wechat_param['keyword1']=$keyword1;
                $wechat_param['keyword2']=$user_use_end_date.'到期';
                $wechat_param['keyword3']='请到我的-红包页面查看';
                $wechat_param['keyword4']='共'.$bonus_amount.'元';
                $wechat_param['remark']='亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾';

                $remark=array();
                $remark['date']=$user_use_end_date;
                $remark['bonus_money']=$bonusqqq['type_money'];
                $remark['min_amount']=$bonusqqq['min_goods_amount'];

                A("Smsapi")->send_message_api_asyn("bonus_expired_reminder",$item['mobile_phone'],$nickname,0,0,0,$item['user_id'],$remark,null,$wechat_param);

                $bonus_id_arr[]=$item['bonus_id'];
            }
            M("user_bonus")->where("bonus_id in (".implode(',',$bonus_id_arr).")")->save(array("is_notice"=>1));
            sleep(5);

        }while($is_notice);


        $is_notice=true;
        do{

            $Model = new Model();
            $bonus_list=$Model->query("select wu.nickname,bt.type_name,group_concat(bt.bonus_discount_type) as bonus_discount_type_str,bt.type_money,group_concat(bt.type_money) as type_money_str,bt.min_goods_amount,group_concat(bt.min_goods_amount) as min_goods_amount_str,bt.use_end_date,ub.bonus_sn,group_concat(ub.bonus_id) as bonus_id,ub.deadline,u.user_name,u.mobile_phone,u.user_id from sdx_user_bonus as ub left join sdx_bonus_type as bt on ub.bonus_type_id=bt.type_id left join sdx_users as u on u.user_id=ub.user_id left join sdx_wechat_user as wu on wu.ect_uid=u.user_id where ((bt.use_end_date > ".local_strtotime(local_date("Y-m-d",local_strtotime("+0 days")))." and bt.use_end_date<".local_strtotime(local_date("Y-m-d",local_strtotime("+1 days"))).") and ub.deadline=0 or (ub.deadline > (".local_strtotime(local_date("Y-m-d",local_strtotime("+0 days"))).") and ub.deadline < (".local_strtotime(local_date("Y-m-d",local_strtotime("+1 days"))).") and bt.has_effective_days=1)) and ub.used_time=0 and ub.user_id>0 and u.platform=0 and u.user_name not like 'wx_196%' ".$where." and ub.is_notice in(0,1) group by ub.user_id limit 600");



            if(count($bonus_list)==0){
                $is_notice=false;
            }

            $bonus_id_arr=array(0);

            foreach($bonus_list as $item){

                //echo $item['user_name'].' -- '.$item['type_name'].' -- '.local_date("Y-m-d",$item['use_end_date']).'<br>';
                $nickname='食得鲜用户';

                if(!empty($item['nickname'])){
                    $nickname=$item['nickname'];
                }

                if($item['deadline']!=0){
                    $user_use_end_date=local_date("Y-m-d",$item['deadline']);
                }else{
                    $user_use_end_date=local_date("Y-m-d",$item['use_end_date']);
                }

                $betweenSecond=strtotime($user_use_end_date)-strtotime(date("Y-m-d"));
                $dayS=$betweenSecond/(24*60*60);
                $dayS+=1;

                $bonus_discount_type_arr=explode(",",$item['bonus_discount_type_str']);
                $min_goods_amount_arr=explode(",",$item['min_goods_amount_str']);
                $type_money_arr=explode(",",$item['type_money_str']);


                $keyword1='';
                $bonus_amount=0;

                $bonusqqq=array('min_goods_amount'=>0,'type_money'=>0);

                foreach($bonus_discount_type_arr as $key=>$val){
                    if($val==1){
                        $keyword1.='满'.$min_goods_amount_arr[$key].'减'.$type_money_arr[$key].'红包 ';
                        $bonus_amount+=$type_money_arr[$key];
                        if($type_money_arr[$key]>$bonusqqq['type_money']){
                            $bonusqqq['min_goods_amount']=$min_goods_amount_arr[$key];
                            $bonusqqq['type_money']=$type_money_arr[$key];
                        }
                    }elseif($val==2){
                        $keyword1.=$type_money_arr[$key].'折红包 ';
                    }
                }





                $wechat_param['url']="https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder";
                $wechat_param['first']='陪你那么久，不想留遗憾！';
                $wechat_param['keyword1']=$keyword1;
                $wechat_param['keyword2']=$user_use_end_date.'到期';
                $wechat_param['keyword3']='请到我的-红包页面查看';
                $wechat_param['keyword4']='共'.$bonus_amount.'元';
                $wechat_param['remark']='亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾';

                $remark=array();
                $remark['date']=$user_use_end_date;
                $remark['bonus_money']=$bonusqqq['type_money'];
                $remark['min_amount']=$bonusqqq['min_goods_amount'];

                A("Smsapi")->send_message_api_asyn("bonus_expired_reminder",$item['mobile_phone'],$nickname,0,0,0,$item['user_id'],$remark,null,$wechat_param);

                $bonus_id_arr[]=$item['bonus_id'];
            }
            M("user_bonus")->where("bonus_id in (".implode(',',$bonus_id_arr).")")->save(array("is_notice"=>4));
            sleep(5);

        }while($is_notice);

        echo 'Success';
    }

    public function test_r(){
        exit();
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");
        echo "已开始运行.........<br/>";
        //M("gift_gct")->where(array("user_id"=>5726))->delete();
        $auto_cache = S("auto_give_bonus");
        if($auto_cache){
            //return false;
        }else{
            //S("auto_give_bonus",1,600);
        }
        if(date("H")!=16&&date("i")!=00){
            //exit("运行时间错误");
        }
        //查询昨天有浏览记录绑定手机用户
        $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();

        $give_address = array();
        foreach ($yesterday_address as $value){
            $give_address[] = $value['uid'];
        }


        //查询昨天有登录标记绑定手机用户
        $yesterday_address_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-115200)) AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();
        //dump(M()->getLastSql());
        $give_address_login = array();
        foreach ($yesterday_address_login as $value){
            $give_address_login[] = $value['uid'];
        }

        //dump($yesterday_address);
        //查询昨天有登录标记地址中有手机用户
        $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-115200)) AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login_login = array();
        foreach ($yesterday_login_login as $value){
            $give_login_login[] = $value['uid'];
        }
        //dump($yesterday_address);
        //查询有浏览商品记录浏览商品记录
        $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-86400)) AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login = array();
        foreach ($yesterday_login as $value){
            $give_login[] = $value['uid'];
        }
        //dump($yesterday_login);
        $old_give_array = array_unique(array_merge($give_login,$give_address,$give_login_login,$give_address_login));

        //dump($old_give_array);
//        exit();
        $array_give = array();
        foreach ($old_give_array as $value){
            //查询此用户今天是否送过红包
            $is_give = M("gift_gct")->where("TO_DAYS(from_unixtime(add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND type in(3,5,10,15)  AND user_id=".$value)->field("id")->count();
            //dump($is_give);
            if($is_give==0) {
                $array_give[] =$value;
            }
        }
        $array_give = array_unique($array_give);


        $new_array = M('user_bonus')->where("bonus_type_id = 144 AND TO_DAYS(from_unixtime(get_time)) = TO_DAYS('2017-07-01 12:44:00')")->getField('user_id',true);
        $update_array = array();
        $delect_array = array();
        foreach($new_array as $value){
            if(in_array($value,$array_give)){
                $update_array[] = $value;
            }else{
                $delect_array[] = $value;
            }
        }
        $update = M('user_bonus')->where("bonus_type_id = 144 AND TO_DAYS(from_unixtime(get_time)) = TO_DAYS('2017-07-01 12:44:00') AND user_id in(".implode(",",$update_array).")")->getField('bonus_id',true);
        $delect = M('user_bonus')->where("bonus_type_id = 144 AND TO_DAYS(from_unixtime(get_time)) = TO_DAYS('2017-07-01 12:44:00') AND user_id in(".implode(",",$delect_array).")")->getField('bonus_id',true);
        //dump($update);
        //dump($delect);
        //exit();
        //$new_array_user_id = array_unique($new_array);
        echo "UPDATE sdx_user_bonus SET deadline=deadline + 86400,get_time=get_time + 86400 WHERE bonus_id IN (".implode(",",$update).")";
        echo "<br/>";
        echo "UPDATE sdx_user_bonus SET deadline=0,get_time=0,user_id=0 WHERE bonus_id IN (".implode(",",$delect).")";
        echo "<br/>";
        echo "UPDATE sdx_gift_gct SET add_time = add_time + 86400  WHERE type=3 and user_id IN (".implode(",",$update_array).")";
        echo "<br/>";
        echo "delete from sdx_gift_gct WHERE type=3 and user_id IN (".implode(",",$delect_array).")";
        echo "<br/>";
        //exit();
        M()->execute("UPDATE sdx_user_bonus SET deadline=deadline + 86400,get_time=get_time + 86400 WHERE bonus_id IN (".implode(",",$update).")");
        M()->execute("UPDATE sdx_user_bonus SET deadline=0,get_time=0,user_id=0 WHERE bonus_id IN (".implode(",",$delect).")");
        M()->execute("UPDATE sdx_gift_gct SET add_time = add_time + 86400  WHERE type=3 and user_id IN (".implode(",",$update_array).")");
        M()->execute("delete sdx_gift_gct WHERE type=3 and user_id IN (".implode(",",$delect_array).")");
    }

    /**
     * 自动取消每天到店自提订单
     */
    public function auto_cancel_order(){
        $auto_cancel_order = S("auto_cancel_order");
        //dump(date("i"));
        if(date("i")!=0||!empty($auto_cancel_order)){
            exit("运行时间错误");
            //echo "运行时间错误";
        }else{
            S("auto_cancel_order",1,10);
        }

        set_time_limit(0);
//        dump(gmtime());
//        dump(time());
        $start_time   = gmtime()-3600;  //一个小时前得数据

        //查询当日晚于当天2130点还未确认收货的自提订单
        $where['pay_time'] = array("lt",$start_time);
        $where['shipping_id'] = 2;  //自提单
        $where['shipping_status'] = array("neq",2); //未确认收获
        $where['order_status'] = array("neq",2);    //未取消
        $where['pay_status'] = array("in",array(2,3));  //已付款/部分退款
        //$where['confirm_time'] = 0;     //无收货时间

        $order_array = M("order_info")->where($where)->getField("order_id",true);
        //dump(M("order_info")->getLastSql());
        //dump($order_array);
        //exit();//2017122714492411228  1992330
        //$order_array = array(1992330);
        $url=C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=Store&a=refund&api=skip";
        foreach ($order_array as $key=>$value){
            $order_shipping = M("order_action")->where(array("order_id"=>$value,"shipping_status"=>2))->count();
            if($order_shipping>0){
                //如订单存在收货确认记录，则不操作退款
                continue;
            }
            $back_goods_list = array(); //退货退款商品列表
            $goods_list= array();
            $sever_goods_list = $this->get_goods_list_real($value,true);
            //判断此有无提交数量超出实际商品剩余量的
            foreach ($sever_goods_list as $key2=>$value2){
                $goods_list['rec_id'] = $value2['rec_id'];
                $goods_list['act_id'] = $value2['act_id'];
                $goods_list['goods_id'] = $value2['goods_id'];
                if($value2['discount_price']>0){
                    $goods_list['goods_price'] = $value2['discount_price'];
                }else{
                    $goods_list['goods_price'] = $value2['goods_price'];
                }
                $goods_list['goods_name'] = urlencode($value2['goods_name']);;
                $goods_list['goods_sn'] = $value2['goods_sn'];
                $goods_list['cnt'] = $value2['real_num'];
                $goods_list['goods_number'] = $value2['real_num'];
                array_push($back_goods_list,$goods_list);
            }

            //执行退货退款操作
            if(count($back_goods_list)>0){
                $order_info = M("order_info")->field("money_paid,surplus,order_amount,refund_amount")->
                where(array("order_id"=>$value))->find();
                $param['order_id'] = $value;
                $param['goods_list'] = json_encode($back_goods_list);
                $param['refund_type'] = '退货退款';
                $param['refund_amount'] = bcsub(bcadd(bcadd($order_info['money_paid'],
                    $order_info['surplus'], 2),
                    $order_info['order_amount'], 2),
                    $order_info['refund_amount'], 2); //最大退款金额;
                $param['user_name'] = '1小时自动取消:alarmcheck/auto_cancel_order';
                $param['admin_user'] = '1小时自动取消:alarmcheck/auto_cancel_order';
                $param['is_recycling'] = '0';
                $param['refund_note'] = "未自提订单自动取消";
                $back_state = $this->rui_http_post($url,$param);
                if($back_state){
                    //returnApiSuccess(null,"取消订单成功,您所支付的金额将原路退款");
                }else{
                    //returnApiError("取消订单失败，请重试");
                }
            }else{
                //returnApiError("已结退款了");
            }
        }
    }

    public function rui_http_post($url, $param){
        $post_file=false;
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            $res = json_decode($sContent,true);
            dump($res);
            if($res['error']){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    /**
     * 获取订单内剩余商品数
     * @param $order_id
     * @return mixed
     */
    public function get_goods_list_real($order_id,$no_gift =  false){
        $buy_goods_list = $this->get_goods_list_by_order($order_id,$no_gift);
        //dump($buy_goods_list);

        $refund_goods_list = $this->get_refund_goods_list($order_id);
        //dump($refund_goods_list);
//        exit();
        foreach ($buy_goods_list as $key=>$value){
            $buy_goods_list[$key]['cat_id'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('cat_id');
            $edit_goods = true;
            foreach ($refund_goods_list as $key2=>$value2){
                if($value['rec_id']==$value2['order_goods_id']){
                    $buy_goods_list[$key]['real_num'] = $value['goods_number']-$value2['refund_number'];
                    $edit_goods = false;
                }
            }
            if($edit_goods){
                $buy_goods_list[$key]['real_num'] = $value['goods_number'];
            }
            if($buy_goods_list[$key]['real_num']==0){
                unset($buy_goods_list[$key]);
            }
        }
        //dump($buy_goods_list);
        //echo "ddddddddd";
        //exit();
        return $buy_goods_list;
    }

    /**
     * 根据订单ID获取订单里面的原始商品（未退款之前的）
     * @param $order_id
     * @return mixed
     */
    private function get_goods_list_by_order($order_id,$no_gift=false){
        if($no_gift){
            $where['order_id'] = $order_id;
            $where['giving'] = array("neq",1);
            return M("order_goods")->where($where)->select();
        }else{
            return M("order_goods")->where(array("order_id"=>$order_id))->select();
        }
    }

    /**
     * 查询订单的退款商品记录
     * @param $order_id
     * @return mixed
     */
    private function get_refund_goods_list($order_id){
        $refund_detail = M("refund_detail")->field("order_goods_id,sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number,goods_id,goods_name,goods_sn ")->where(array("order_id"=>$order_id))->group('order_goods_id')->select();
        //dump(M("refund_detail")->getlastsql());
        return $refund_detail;
    }
}